import { showNotification } from '../utils//notification'
import fs from 'node:fs'
import path from 'node:path'
import { McpServerConfig } from './types'
import { shell } from 'electron'
import { debounce } from 'lodash'

let mcpConfig

let timeoutId

const DEBOUNCE_DELAY = 500

function handleFileChange(configPath) {
  try {
    const parsedConfig = readConfig(configPath)
    if (mcpConfig !== parsedConfig) {
      console.log(`${configPath} changed`)
    }
  } catch {}
}

const debouncedHandleFileChange = debounce(handleFileChange, DEBOUNCE_DELAY)

function readConfig(configPath: string) {
  const fileString = fs.readFileSync(configPath, 'utf8')
  if (fileString) {
    return JSON.parse(fileString)
  } else {
    return {}
  }
}

export function loadConfigFile(configPath: string): Record<string, McpServerConfig> {
  const resolvedConfigPath = path.isAbsolute(configPath)
    ? configPath
    : path.resolve(process.cwd(), configPath)

  try {
    if (!fs.existsSync(resolvedConfigPath)) {
      showNotification({
        body: `MCP Config Not Found.`
      })
      return {}
    }
    const parsedConfig = readConfig(resolvedConfigPath)
    mcpConfig = parsedConfig
    fs.watch(resolvedConfigPath, () => {
      if (timeoutId) clearTimeout(timeoutId)
      timeoutId = setTimeout(() => debouncedHandleFileChange(resolvedConfigPath), DEBOUNCE_DELAY)
    })
    if (!parsedConfig.mcpServers) {
      return {}
    } else {
      return parsedConfig.mcpServers
    }
  } catch (err) {
    showNotification(
      {
        body: `MCP Config JSON parse failure`
      },

      {
        onClick: () => {
          shell.showItemInFolder(resolvedConfigPath)
        }
      }
    )
    if (err instanceof SyntaxError) {
      throw new Error(`Invalid JSON in config file: ${err.message}`)
    }
    throw err
  }
}

export function loadLlmFile(llmPath: string) {
  const resolvedConfigPath = path.isAbsolute(llmPath)
    ? llmPath
    : path.resolve(process.cwd(), llmPath)
  try {
    if (!fs.existsSync(resolvedConfigPath)) {
      throw new Error(`Config file not found: ${resolvedConfigPath}`)
    }
    const configContent = fs.readFileSync(resolvedConfigPath, 'utf8')
    const parsedConfig = JSON.parse(configContent)
    if (!parsedConfig) {
      return {}
    } else {
      return parsedConfig
    }
  } catch (err) {
    showNotification(
      {
        body: 'LLM Config JSON parse failure'
      },

      {
        onClick: () => {
          shell.showItemInFolder(resolvedConfigPath)
        }
      }
    )
    if (err instanceof SyntaxError) {
      throw new Error(`Invalid JSON in llm file: ${err.message}`)
    }
    throw err
  }
}
